<template>
  <div id="drawer-target" class="recentTaskListWrap">
    <div class="header">
      <div class="title">
        <div class="divide" />
        {{ creatTaskShow ? taskType : "近期任务" }}
      </div>
      <div v-if="!creatTaskShow" class="createTask" @click="createTask">
        <n-icon size="20">
          <FileAddOutlined />
        </n-icon>
        <div class="text" style="margin-left: 5px">新增</div>
      </div>
      <div v-if="creatTaskShow" class="close" @click="closeCreate">
        <n-icon size="20">
          <CloseOutlined />
        </n-icon>
      </div>
    </div>
    <!--  近期任务列表  -->
    <div v-if="!creatTaskShow" class="taskListWrap">
      <div v-if="!creatTaskShow" class="taskListWrap">
        <div
          v-for="(item, index) in inspectionList.slice(0, 5)"
          :key="index"
          :class="{ activeTaskItem: index === activeIndex }"
          class="taskListItem"
          @click="handleTaskClick(item, index)"
        >
          <div class="taskLine" style="justify-content: space-between">
            <div class="leftWrap">
              <div class="title">任务名称：</div>
              <div class="value taskName">{{ item.name }}</div>
            </div>
            <div class="rightWrap">
              <div
                v-for="(item, index) in TASK_AIRPORT_STATUS.filter(
                  (it) => it.value === item.status
                )"
                :key="index"
                class="status"
                :style="{ background: item.color }"
              >
                {{ item.label }}
              </div>
            </div>
          </div>
          <!--          <div class="taskLine">-->
          <!--            <div class="title">任务类型：</div>-->
          <!--            <div class="value">{{ TASK_TYPE.filter(it => it.value === item.type)[0].label }}</div>-->
          <!--          </div>-->
          <div class="taskLine">
            <div class="title">巡检时间：</div>
            <div class="value">{{ item.inspectionTime }}</div>
          </div>
          <div class="taskLine">
            <div class="title">巡检方式：</div>
            <div class="value">
              {{
                item.airportName
                  ? TASK_INSPECTS.filter(
                    (i) => i.value === item.inspectionType
                  )[0].label +
                    "-" +
                    item.airportName
                  : TASK_INSPECTS.filter(
                    (i) => i.value === item.inspectionType
                  )[0].label
              }}
            </div>
          </div>
          <div
            v-if="item.status === 5 && item.inspectionType !== 3"
            class="button nowClass"
            @click="execute(item, $event)"
          >
            立即执行
          </div>
          <div
            v-if="item.status === 10 || item.status === 6"
            class="button playClass"
            @click="checkLive(item, $event)"
          >
            查看直播
          </div>
          <div
            v-if="item.status === 15"
            class="button playClass"
            @click="checkReturn(item, $event)"
          >
            查看回放
          </div>
        </div>
        <div class="taskListItemMore" @click="goTaskListAll">查看更多任务</div>
      </div>
    </div>
    <div v-if="creatTaskShow" class="creatTaskWrap">
      <n-form
        ref="newTaskFormRef"
        :model="newTaskForm"
        :label-width="130"
        :rules="newTaskRule"
        label-placement="left"
      >
        <n-form-item path="name" label="任务名称:">
          <n-input
            v-model:value.trim="newTaskForm.name"
            @keydown.enter.prevent
          />
        </n-form-item>
        <n-form-item path="inspectionType" label="巡检方式:">
          <n-select
            v-model:value="newTaskForm.inspectionType"
            :options="inspectionTypeOption"
            @update:value="handleInspectionTypeChange"
          />
        </n-form-item>
        <n-form-item path="inspectionTime" label="期望监测时间:">
          <n-date-picker
            ref="dateRef"
            v-model:formatted-value="newTaskForm.inspectionTime"
            type="datetime"
            :format="'yyyy-MM-dd HH:mm:ss'"
            :is-date-disabled="disablePreviousDate"
            clearable
          />
        </n-form-item>
        <div v-if="isAirportShow" class="flyoptions">
          <n-form-item path="airportId" label="机场:">
            <n-select
              v-model:value="newTaskForm.airportId"
              :options="airportOption"
              @change="changeAirport"
            />
          </n-form-item>
          <n-form-item path="inspectionLine" label="巡检航线:" >
            <n-select
              v-if="!isNewLine"
              v-model:value="newTaskForm.inspectionLine"
              :options="inspectionLineOption"
              @change="changeAirLine"
              style="width: 250px;"
            />
            <!-- <n-input
              v-else
              v-model:value="newLineForm.airportLineName"
              @keydown.enter.prevent
            /> -->
            <!-- 选择下拉框的航线之后，隐藏新增按钮 -->
            <!-- <n-button v-if="!newTaskForm.inspectionLine"  color="#394C73" @click="createNewLine">新增</n-button> -->
          </n-form-item>
          <div v-if="!isNewLine">
            <n-form-item path="flyHeight" label="飞行高度:">
              <n-slider
                v-model:value="newTaskForm.flyHeight"
                :max="500"
                disabled
              />
            </n-form-item>
          </div>
          <div v-if="isNewLine">
            <n-form
              ref="newLineFormRef"
              :model="newLineForm"
              :label-width="130"
              :rules="newLineRuler"
              label-placement="left"
            >
              <!-- <n-form-item path="airportLineName" label="航线名称:">
                <n-input v-model:value="newLineForm.airportLineName" @keydown.enter.prevent />
              </n-form-item> -->
              <n-form-item path="region" label="选择区域:">
                <n-input
                  v-model:value="newLineForm.region"
                  placeholder="请选择区域"
                  disabled
                />
                <div class="positonBtn" @click="selectRegion" />
              </n-form-item>
              <n-form-item path="altitude" label="飞行高度:">
                <n-slider v-model:value="newLineForm.altitude" :max="500" />
              </n-form-item>
              <n-form-item path="interval" label="间隔:">
                <n-slider v-model:value="newLineForm.interval" :max="500" />
              </n-form-item>
              <n-form-item path="angle" label="角度:">
                <n-slider v-model:value="newLineForm.angle" :max="360" />
              </n-form-item>
            </n-form>
          </div>
        </div>
        <div v-if="!isAirportShow" class="flyOptions">
          <n-form-item>
            <map-comp ref="gmapRef" class="mapCom" @map-emit="getLnglat" />
          </n-form-item>
          <div style="margin-top: -20px">
            注意：请选择实际执飞点周边经纬度，请勿偏离。
          </div>
          <n-form-item path="startPoint" label="起点:">
            <n-input
              v-model:value="newTaskForm.startLongitude"
              placeholder="经度"
              style="width: 50%"
            />
            <n-input
              v-model:value="newTaskForm.startLatitude"
              placeholder="纬度"
              style="width: 50%"
            />
            <div class="positonBtn" @click="position('start')" />
          </n-form-item>
          <n-form-item path="endPoint" label="终点:">
            <n-input
              v-model:value="newTaskForm.endLongitude"
              placeholder="经度"
              style="width: 50%"
            />
            <n-input
              v-model:value="newTaskForm.endLatitude"
              style="width: 50%"
              placeholder="纬度"
            />
            <div class="positonBtn" @click="position('end')" />
          </n-form-item>
          <n-form-item path="mobile" label="联系方式:" >
            <n-input v-model:value="newTaskForm.mobile" maxlength="18"/>
          </n-form-item>
          <n-form-item path="note" label="备注:">
            <n-input
              v-model:value="newTaskForm.note"
              type="textarea"
              placeholder="备注"
              maxlength="200" show-count
            />
          </n-form-item>
        </div>
        <n-form-item style="margin-left: 65px">
          <n-button
            color="#394C73"
            class="btn"
            @click="closeCreate"
          >取消</n-button>
          <n-button
            v-if="isAirportShow && isNewLine"
            class="btn"
            @click="sumbitNewLine"
          >生成航线</n-button>
          <n-button
            type="info"
            class="btn"
            @click="submitNewTask"
          >保存</n-button>
        </n-form-item>
      </n-form>
    </div>
  </div>
</template>

<script setup>
import MapComp from '@/components/MapComp/MapComp.vue'
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { getInspectionList } from '@/api/inspection/index.js'
import { CloseOutlined, FileAddOutlined } from '@vicons/antd'
import { getAirList, getLineList, taskAdd, getTaskByID, taskEditNew, getAirLineByAir } from '@/api/task/index.js'
import { routeByTask , routeByline } from '@/api/dashboard/index.js'
import { getFlightData } from '@/api/flight-data/index.js'
import { TASK_AIRPORT_STATUS, TASK_INSPECTS, TASK_TYPE } from '@/utils/dictionary'
import { useRouter, useRoute } from 'vue-router'
import { fromLonLat } from 'ol/proj'
import axios from 'axios'
import { FALSE } from 'ol/functions'
import { debounce } from '@/utils/index.js'
const props = defineProps({
  inspectionList: {
    type: Array,
    default: () => {
      return
    }
  },
  gisMap: {
    type: Object,
    default: () => {
      return ref()
    }
  },
  airportList: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['openModal', 'setRegion', 'newLine', 'openLive', 'openReturn', 'changeRouteParams', 'clearDraw'])
// data
const newTaskFormRef = ref(null)
const newLineFormRef = ref(null)
const gmapRef = ref()
const creatTaskShow = ref(false)
const currentTask = ref(null)
const route = useRoute()
const taskType = ref('新增任务')
onMounted(() => {
  nextTick(() => {
    switch (route.query?.type) {
      case 'edit':
        creatTaskShow.value = route.query.flag
        taskType.value = '编辑任务'
        getTaskInfo()
        break
      case 'create':
        creatTaskShow.value = route.query.flag
        taskType.value = '新增任务'
        break
      case 'preview':
        getTaskInfo()
        // inspectionItem.value = props.inspectionList.filter(item => item.id === route.query.taskId)
        // console.log('playVideoInfoData', playVideoInfoData.value)
        // emit('openReturn', ...inspectionItem.value)
        break
      case 'live':
        getTaskInfo()
        // inspectionItem.value = props.inspectionList.filter(item => item.id === route.query.taskId)
        // console.log('走到这里了', route.query.taskId, inspectionItem)
        // emit('openLive', ...inspectionItem.value)
        break
    }
  })
})
// 根据id查询任务
const getTaskInfo = (type) => {
  if (route.query.taskId) {
    getTaskByID(route.query.taskId).then(res => {
      if (res.code === 0) {
        switch (route.query?.type) {
          case 'edit':
            Object.assign(newTaskForm, { ...res.data })
            break
          case 'preview':
            emit('openReturn', { ...res.data })
            break
          case 'live':
            emit('openLive', { ...res.data })
            break
        }
      }
    })
  }
}
class TaskForm {
  name = null // 任务名称
  inspectionType = 2 // 巡检方式
  airportId = null // 机场
  airportName = null // 机场名称
  inspectionLine = null // 巡检航线
  inspectionLineName = null // 航线名称
  isLive = null // 是否直播 1实时 2离线 默认null
  inspectionTime = null // 期望监测时间
  flyHeight = null // 飞行高度
  startLongitude = null // 起始点经度
  startLatitude = null // 起始点纬度
  endLongitude = null // 终点经度
  endLatitude = null // 终点纬度
  mobile = null // 联系方式
  lineName = null // 航线名称
  note = null
  droneId = null // 无人机id
}

const newTaskForm = reactive(new TaskForm())

class LineForm {
  airportLineName = null
  airportRouteDtoList = []
  altitude = null
  inspectionRegionDtoList = []
  region = null
  interval = null
  angle = null
}
const newLineForm = reactive(new LineForm())

const newTaskRule = reactive({
  name: {
    required: true,
    message: '请输入任务名称',
    trigger: 'blur'
  },
  inspectionType: {
    required: true,
    message: '请选择巡检方式'
  },
  airportId: {
    required: true,
    message: '请选择机场'
  },
  inspectionLine: {
    required: true,
    message: '请选择航线'
  },
  inspectionTime: {
    required: true,
    message: '请选择时间'
  },
  startPoint: {
    required: true,
    message: '请选择起始点',
    validator: (rule, value) => {
      if (!newTaskForm.startLongitude || !newTaskForm.startLatitude) {
        return false
      }
    }
  },
  endPoint: {
    required: true,
    message: '请选择终止点',
    validator: (rule, value) => {
      if (!newTaskForm.endLongitude || !newTaskForm.endLatitude) {
        return false
      }
    }
  },
  mobile: {
    required: true,
    message: '请提供联系方式'
  }
})

const newLineRuler = reactive({
  airportLineName: {
    required: true,
    message: '请输入航线名称',
    trigger: 'blur'
  },
  altitude: {
    required: true,
    message: '请指定高度'
  }

})

const inspectionTypeOption = ref([
  {
    label: '机场巡检',
    value: 2
  },
  {
    label: '人工执飞',
    value: 3
  }
])

// 机场选择下拉框选项，由接口获取
const airportOption = reactive([])

const inspectionLineOption = reactive([])// 航线下拉框选项，接口获取

const isAirportShow = ref(true)

const airportsInfo = reactive([]) // 机场所有信息

const isNewLine = ref(false)

const inspectionLineList = reactive([])// 所有航线信息

// functions

// 时间选择器
function disablePreviousDate(ts) {
  return ts < Date.now() - 86400000
}
function selectRegion() {
  if (!newTaskForm.airportId) {
    $message.error('请先选择机场')
  } else {
    const info = {
      airportId: currentAirport.value.id,
      lineType: null,
      altitude: null,
      interval: 50,
      angle: 0,
      channelId: null,
      legId: null,
      longitude: currentAirport.value.longitude,
      latitude: currentAirport.value.latitude
    }
    emit('setRegion', info)
  }
}

function clearDraw() {
  emit('clearDraw')
}

function createNewLine() {
  clearDraw()
  isNewLine.value = !isNewLine.value
}
function sumbitNewLine() {
  newLineFormRef.value?.validate((errors) => {
    if (!errors) {
      const info = {
        airportId: currentAirport.value.id,
        lineType: null,
        altitude: newLineForm.altitude,
        interval: newLineForm.interval,
        angle: newLineForm.angle,
        channelId: null,
        legId: null,
        longitude: currentAirport.value.longitude,
        latitude: currentAirport.value.latitude,
        name: newLineForm.airportLineName
      }
      emit('newLine', info)
    } else {
      console.log(errors)
      console.log('Valid')
    }
  })
}
// 通过航线文件获取航线高度
function getHeight(url) {
  console.log(url)
  axios.get(url).then(res => {
    if (res.status === 200) {
      const text = res.data
      // let arr = text.split('\r\n')
      let arr = text.split('\n')
      arr.shift()
      arr.pop()
      arr = arr.map((text) => {
        return text.split(/\s+/)
      })
      newTaskForm.flyHeight = arr[1][10]
    }
  })
}

const activeIndex = ref(-1)
function handleTaskClick(task, index) {
  if (!props.gisMap) return
  clearRouteTrack()
  activeIndex.value = index
  // 点击同一任务两次取消选中
  if (task.id === currentTask.value?.id) {
    activeIndex.value = -1
    currentTask.value = null
    return
  }
  currentTask.value = task
  // 判断是机场巡检or飞手执飞任务
  if (task.inspectionType === 2) { // 机场巡检
    switch (task.status) {
      case 5:// 待飞行
        drawRoute(task)
        break
      case 6:// 准备中
        drawRoute(task)
        break
      case 7:// 飞行失败

        break
      case 10:// 飞行中
        drawRoute(task)
        drawRealTimeTrack(task.id)
        break
      case 15:// 飞行完成
        drawTrack(task.id)
        break

      default:
        break
    }
  } else if (task.inspectionType === 3) { // 飞手执飞
    switch (task.status) {
      case 5:// 待飞行
        drawInitialPoint(task)
        break
      case 6:// 准备中
        drawInitialPoint(task)
        break
      case 7:// 飞行失败

        break
      case 10:// 飞行中
        drawInitialPoint(task)
        drawRealTimeTrack(task.id)
        break
      case 15:// 飞行完成
        drawInitialPoint(task)
        drawTrack(task.id)
        break

      default:
        break
    }
  }

  // drawRoute(task)
  // drawTrack(task.id)
  // drawRealTimeTrack(task.id)
}

// 根据任务id获取航线
// async function getTaskRoute(id) {
//   const res = await routeByTask(id)
//   const airLine = res.data.data
//   return Promise.resolve({
//     airLine
//   })
// }

// 根据航线id获取航线
async function getTaskRoute(id) {
  const res = await routeByline(id)
  const airLine = res.data
  const fileUrl = airLine.fileUrl
  return axios.get(fileUrl).then(res => {
    let lngLatsArr = []
    let lngLats = []
        if (res.status === 200) {
          const text = res.data
          let arr = text.split('\n')
          arr.shift()
          arr.pop()
          arr = arr.map((text) => {
            return text.split(/\s+/)
          })
          arr.forEach(e => {
            if (e[9] * 1 === 0 || e[8] * 1 === 0) return
            const coord = [e[9] * 1, e[8] * 1]
            lngLatsArr.push(coord)
          })
          lngLats = lngLatsArr.map(item => {
            return {
              lon: item[0],
              lat: item[1]
            }
          })
          // addAirLineLayer(lngLats)
        }
        return Promise.resolve({
          lngLats
        })
      })
}

// 根据任务id获取轨迹
async function getTaskTrack(id) {
  const res = await getFlightData(id)
  if (res.code !== 0 || res.data.length === 0) return
  const trackList = res.data
  return Promise.resolve({
    trackList
  })
}
// 画出任务航线
async function drawRoute(task) {
  console.log(task,'task是什么')
  const id = task.inspectionLine

  // getTaskRoute(id)
   const res =  await getTaskRoute(id)
  console.log('画航线',id,res)

    props.gisMap.drawDroneRoute(res.lngLats, task.airportId)
}

// 画出轨迹
function drawTrack(id) {
  console.log('画出轨迹')
  getTaskTrack(id).then(res => {
    if (!res) {
      console.log('轨迹为空,任务id为', id)
      return
    }
    props.gisMap.drawTrack(res.trackList)
  })
}

// 画出起始点
const pointLayers = ref([])
function drawInitialPoint(task) {
  const points = [
    {
      coordinates: [
        {
          longitude: task.startLongitude,
          latitude: task.startLatitude
        }
      ],
      options: {
        type: 'start',
        amap_coord: true
      }
    }, {
      coordinates: [
        {
          longitude: task.endLongitude,
          latitude: task.endLatitude
        }
      ],
      options: {
        type: 'end',
        amap_coord: true
      }
    }
  ]
  points.forEach(point => {
    const layer = props.gisMap.addPointLayer(point.coordinates, point.options)
    pointLayers.value.push(layer.pointLayer)
  })
  const extent = props.gisMap.getLayerExtent(pointLayers.value)
  props.gisMap.fitExtent(extent)
}

const trackInterval = ref(null)
// 画出实时轨迹
function drawRealTimeTrack(id) {
  trackInterval.value = setInterval(() => {
    drawTrack(id)
  }, 2000)
}
// 清除直播轨迹定时器
function clearTrackInterval() {
  if (trackInterval.value) {
    clearInterval(trackInterval.value)
    trackInterval.value = null
  }
}
// 清除轨迹、航线、起始点图层
function clearRouteTrack() {
  clearTrackInterval()
  // props.gisMap.clearRouteLayer()
  props.gisMap.clearTrack()
  if (pointLayers.value.length > 0) {
    pointLayers.value.forEach(layer => {
      props.gisMap.removeLayer(layer)
    })
    pointLayers.value = []
  }
}
// 创建任务
const createTask = () => {
  clearRouteTrack()
  activeIndex.value = -1
  creatTaskShow.value = true
  isNewLine.value = false
  resetData()
}

const closeCreate = () => {
  clearDraw()
  creatTaskShow.value = false
  router.push({
    path: '/home'
  })
}
const execute = (item, e) => {
  e.stopPropagation()
  emit('openModal', item)
}

const checkLive = (item, e) => {
  e.stopPropagation()
  emit('openLive', item)
}
const checkReturn = (item, e) => {
  e.stopPropagation()
  emit('openReturn', item)
}
const router = useRouter()
const goTaskListAll = () => {
  router.push({
    path: '/task-manage/task-all'
  })
}
// 获取最近任务列表
function getList() {
  getInspectionList().then(res => {
  })
}
function getAirportList() {
  if (props.airportList.length > 0) {
    props.airportList.forEach((e, index) => {
      airportsInfo.push(e)
      const Option = {
        label: e.name,
        value: e.id
      }
      airportOption.push(Option)
    })
  }
}

// function getAirportList() {
//   getAirList().then(res => {
//     if (res.code === 0) {
//       res.data.records
//       res.data.records.forEach((e, index) => {
//         airportsInfo.push(e)
//         const Option = {
//           label: e.name,
//           value: e.id
//         }
//         airportOption.push(Option)
//       })
//     }
//   })
// }
// 切换机场
function changeAirport() {
  newTaskForm.inspectionLine = null
  newTaskForm.inspectionLineName = null
}
// 切换巡检航线
async function changeAirLine(value) {
  newTaskForm.flyHeight = null
  if (value === null) return
  const currentLine = inspectionLineList.filter(e => e.id === value)
  if (currentLine.length > 0) {
    getHeight(currentLine[0].fileUrl)
    console.log('调用完高度，绘制航线',value)
    const res =await  getTaskRoute(value)
    console.log('最新绘制航线',newTaskForm,res,'-----',newTaskForm.airportId)//airportId是当前数据返回
    console.log(res.lngLats[0].lon,typeof(res.lngLats[0].lon)=='number')
    if((!isNaN(res.lngLats[0].lon))){
      console.log('走到if')
      props.gisMap.drawDroneRoute(res.lngLats, newTaskForm.airportId)

    }
  }
  newTaskForm.inspectionLineName = currentLine[0]?.name
  newTaskForm.inspectionLine = currentLine[0]?.id
}
// 保存任务
const submitNewTask = debounce(() => {
  if (isNewLine.value) {
    $message.error('请先生成航线')
    return
  }
  const txt = new RegExp("[ ,\\￥,\\`,\\~,\\!,\\@,\#,\\$,\\%,\\^,\\+,\\*,\\&,\\\\,\\/,\\?,\\|,\\:,\\.,\\<,\\>,\\{,\\},\\(,\\),\\',\\;,\\=,\"]")
  if (txt.test(newTaskForm.name)) {
    $message.error('航线名称中不允许存在特殊字符或空格')
    return
  }
  newTaskFormRef.value?.validate((errors) => {
    if (!errors) {
      const airportList = props.airportList
      const currentAirport = airportList.filter(e => e.id === newTaskForm.airportId)
      newTaskForm.droneId = currentAirport[0]?.droneId || null
      if (route.query.taskId && route.query.type === 'edit') {
        taskEditNew(newTaskForm).then(res => {
          if (res.code === 0) {
            resetData()
            creatTaskShow.value = false
          }
        })
      } else {
        taskAdd(newTaskForm).then(res => {
          if (res.code === 0) {
            resetData()
            creatTaskShow.value = false
          }
        })
      }
    } else {
      console.log(errors)
      console.log('Valid')
    }
  })
}, 2000, true)

function resetData() {
  Object.assign(newTaskForm, new TaskForm())
  Object.assign(newLineForm, new LineForm())
}

// function inspectionReset(type) {
//   newTaskForm.airportId = null
//   newTaskForm.airportName = null
//   newTaskForm.inspectionLine = null
//   newTaskForm.inspectionLineName = null
//   newTaskForm.inspectionTime = null
//   newTaskForm.flyHeight = null
//   newTaskForm.startLongitude = null
//   newTaskForm.startLatitude = null
//   newTaskForm.endLongitude = null
//   newTaskForm.endLatitude = null
//   newTaskForm.mobile = null
//   newTaskForm.lineName = null
//   newTaskForm.note = null
//   newTaskForm.droneId = null
// }

function resetLineForm() {
  Object.assign(newLineForm, new LineForm())
}

const newLineSuccess = (lineObj) => {
  console.log(lineObj)
  resetLineForm()
  isNewLine.value = false
  newTaskForm.inspectionLine = lineObj.inspectionLineId
  newTaskForm.inspectionLineName = lineObj.airportLineName
  getHeight(lineObj.ossUrl)
}

// 根据机场的无人机id获取关联的航线列表
function getAirportLine() {
  const taskList = airportsInfo.filter(e => e.id === newTaskForm.airportId)
  if (taskList.length === 0) return
  currentAirport.value = taskList[0]
  newTaskForm.airportName = taskList[0].name
  const airportId = taskList[0].id
  inspectionLineOption.splice(0, inspectionLineOption.length)
  getAirLineByAir(airportId).then(res => {
    if (res.code === 0 && res.data.length > 0) {
      const list = res.data
      list.forEach(e => {
        inspectionLineList.push(e)
        const options = {
          label: e.fileName,
          value: e.id
        }
        inspectionLineOption.push(options)
      })
    }
  })
}

// // 用于存放map组件取到的点位值
// const lngLatTemp = {
//   lng: 0,
//   lat: 0
// }
function getLnglat(lngLat) {
  if (onStart.value) {
    newTaskForm.startLongitude = parseFloat(lngLat.R)
    newTaskForm.startLatitude = parseFloat(lngLat.Q)
    console.log(lngLat,newTaskForm.startLongitude,'921');
  } else if (onEnd.value) {
    newTaskForm.endLongitude = parseFloat(lngLat.R)
    newTaskForm.endLatitude = parseFloat(lngLat.Q)
  }
  onStart.value = onEnd.value = false
}

const onStart = ref(false)
const onEnd = ref(false)
function position(type) {
  if (type === 'start') {
    onEnd.value = false
    onStart.value = true
  } else {
    onStart.value = false
    onEnd.value = true
  }
}
// 执行区
getList()
function handleInspectionTypeChange(value, option) {
  // console.log(newTaskForm.name)
  // 切换巡检方式，保留已经输入的任务名称
  const taskName=newTaskForm.name
  // inspectionReset(value)
  resetData()
  newTaskForm.name=taskName
  newTaskForm.inspectionType = value
  if (value === 2) {
    isAirportShow.value = true
  } else {
    isAirportShow.value = false
  }
}

// watch(() => newTaskForm.inspectionType, (newV, oldV) => {
//   // if (oldV !== null) {
//   //   // resetData()
//   // }
//   // newTaskForm.inspectionType = newV
//   if (newV === oldV) return

//   if (newV === null) {
//     isAirportShow.value = true
//     return
//   }
//   if (newV === 2) {
//     isAirportShow.value = true
//   } else {
//     isAirportShow.value = false
//   }
// }, {
//   deep: true
// })

watch(() => props.airportList, (newV) => {
  getAirportList()
  getAirportLine()
}, {
  deep: true
})

const currentAirport = ref({})
watch(() => newTaskForm.airportId, newV => {
  if (newV === null) return
  getAirportLine()
  // newTaskForm.inspectionLine = null
  // newTaskForm.inspectionLineName = null

  if (isNewLine.value) {
    selectRegion()
  }
})

watch(() => newTaskForm.inspectionLine, newV => {
  // newTaskForm.flyHeight = null
  // if (newV === null) return
  // const currentLine = inspectionLineList.filter(e => e.id === newV)
  // if (currentLine.length > 0) {
  //   getHeight(currentLine[0].airlineFileUrl)
  // }
  // newTaskForm.inspectionLineName = currentLine[0]?.name
})

watch(() => newLineForm, newV => {
  if (!newLineForm.angle && !newLineForm.interval) return
  const params = {
    interval: newLineForm.interval,
    angle: newLineForm.angle
  }
  emit('changeRouteParams', params)
}, {
  deep: true
})

onUnmounted(() => {
  clearTrackInterval()
})
defineExpose({
  newLineSuccess, getAirportLine
})
</script>

<style scoped lang="scss">
:deep(.n-input.n-input--textarea){
  padding-bottom: 30px;

}
.recentTaskListWrap {
  width: 420px;
  min-height: 700px;
  background-color: red;
  overflow: auto;
  .header {
    // padding: 22px 0;
    height: 60px;
    line-height: 60px;
    display: flex;
    justify-content: space-between;
    font-size: 20px;

    .title {
      display: flex;
      justify-content: left;

      .divide {
        height: 24px;
        width: 5px;
        margin-top: 17px;
        background: #3b6bec;
        margin-right: 10px;
      }
    }

    .createTask {
      cursor: pointer;
      display: flex;
      justify-content: left;
      align-items: center;
      width: 80px;
      line-height: 20px;
    }

    .close {
      width: 20px;
      color: #fff;
      font-size: 20px;
      cursor: pointer;
    }
  }

  .taskListWrap {
    .taskListItem {
      padding: 10px;
      background: #2a2f46;
      margin-bottom: 10px;

      .taskLine {
        display: flex;
        justify-content: left;
        font-size: 16px;
        .leftWrap {
          display: flex;
          justify-content: left;
          .title{
            text-wrap: nowrap;
          }
        }
        .rightWrap{
          text-wrap: nowrap;
        }

        .taskName {
          color: #82a6ff;
        }

        .status {
          font-size: 12px;
          padding: 2px 4px;
          border-radius: 2px;
        }
      }

      .button {
        margin-top: 10px;
        width: 100%;
        border-radius: 15px;
        height: 36px;
        text-align: center;
        line-height: 36px;
        cursor: pointer;
        color: #fff;
        font-weight: 400;
        font-size: 16px;
        font-family: Source Han Sans CN;
        border: 1px solid #3b6bec;
        letter-spacing: 1px;
        // background: linear-gradient(0deg, #5082FB, #3E6EEC);
      }
      .nowClass {
        background: linear-gradient(0deg, #5082fb, #3e6eec);
      }
      .playClass {
        background: #304c8a;
      }
    }
    .activeTaskItem {
      border: 1px solid #3b6bec;
    }
    .taskListItemMore {
      height: 45px;
      line-height: 45px;
      font-size: 18px;
      text-align: center;
      background: #2a2f46;
      cursor: pointer;
    }
    .checkMore {
      width: 100%;
      font-size: 18px;
      background: #2a2f46;
      text-align: center;
      padding: 10px;
      cursor: pointer;
    }
  }
}

.btn {
  margin: 0 20px;
}

.positonBtn {
  width: 34px;
  height: 34px;
  background: url(@/assets/gis/xuanzequyu@2x.png) no-repeat;
  background-size: cover;
}
.mapCom{
  height: 270px;
}

:deep .n-form-item-label__text {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #fffefe;
  line-height: 25px;
}
:deep(.sugg-item) {
  color: black;
}
</style>
